package tools

import (
	"app-box/api_error"
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"io"
	"mime/multipart"
	"os"
	"path/filepath"
)

func PanicFileMD5Check(md5Str string, fileHeader multipart.FileHeader) {
	file, err := fileHeader.Open()
	defer file.Close()
	if err != nil {
		panic(api_error.IOError(err))
	}
	md5Ctx := md5.New()
	io.Copy(md5Ctx, file)
	newMd5Str := hex.EncodeToString(md5Ctx.Sum(nil))
	if newMd5Str != md5Str {
		panic(api_error.InvalidFileError())
	}
}

func SaveFileTo(file multipart.FileHeader, dst string) {
	src, err := file.Open()
	if err != nil {
		panic(api_error.IOError(err))
	}
	defer src.Close()
	dstDir, _ := filepath.Split(dst)
	if err := os.MkdirAll(dstDir, 0755); err != nil {
		panic(api_error.IOError(err))
	}
	out, err := os.Create(dst)
	if err != nil {
		panic(api_error.IOError(err))
	}
	defer out.Close()
	_, err = io.Copy(out, src)
	if err != nil {
		panic(api_error.IOError(err))
	}
}

func SaveDataTo(data []byte, dst string) {
	dstDir, _ := filepath.Split(dst)
	if err := os.MkdirAll(dstDir, 0755); err != nil {
		panic(api_error.IOError(err))
	}
	out, err := os.Create(dst)
	if err != nil {
		panic(api_error.IOError(err))
	}
	defer out.Close()
	bytesBuffer := bytes.NewBuffer(data)
	_, err = io.Copy(out, bytesBuffer)
	if err != nil {
		panic(api_error.IOError(err))
	}
}

func CopyFile(srcFile, destFile string) (int64, error) {
	dstDir, _ := filepath.Split(destFile)
	if err := os.MkdirAll(dstDir, 0755); err != nil {
		panic(api_error.IOError(err))
	}
	file1, err := os.Open(srcFile)
	if err != nil {
		return 0, err
	}
	file2, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE, os.ModePerm)
	if err != nil {
		return 0, err
	}
	defer file1.Close()
	defer file2.Close()
	return io.Copy(file2, file1)
}

func FileExist(path string) bool {
	_, err := os.Lstat(path)
	return !os.IsNotExist(err)
}
